﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StripeOne.ShortenUrl.Database;
using System.Data.EntityClient;
using System.Data.SqlClient;
using StripeOne.Core.Log;
using StripeOne.ShortenUrl.Datalayer.Base;

namespace StripeOne.ShortenUrl.Datalayer
{
    public class ShortenUrlDatalayerBase
    {
        public ShortenUrlDatalayerBase()
        {
        }

        private readonly StripeOneDatabaseConfig _config { get { return new StripeOneDatabaseConfig(); } }
        public static ShortenUrlEntities GetContext()
        {
            try
            {
                return new ShortenUrlEntities(GetConnectionString().ConnectionString);
            }
            catch (Exception ex)
            {
                StripeOneLog.Exception(ex);
                throw;
            }
        }

        private static EntityConnectionStringBuilder GetConnectionString()
        {
            try
            {
                var sqlConn = new SqlConnectionStringBuilder();
                sqlConn.DataSource = StripeOneDatabaseConfig.Default.DataSource;
                sqlConn.InitialCatalog = StripeOneDatabaseConfig.Default.InitialCatalog;
                sqlConn.PersistSecurityInfo = StripeOneDatabaseConfig.Default.PersistSecurityInfo;
                sqlConn.UserID = StripeOneDatabaseConfig.Default.User;
                sqlConn.Password = StripeOneDatabaseConfig.Default.Password;

                var conn = new EntityConnectionStringBuilder();
                conn.Metadata = StripeOneDatabaseConfig.Default.Metadata;
                conn.Provider = StripeOneDatabaseConfig.Default.Provider;
                conn.ProviderConnectionString = sqlConn.ConnectionString;

                return conn;
            }
            catch (Exception ex)
            {
                StripeOneLog.Exception(ex);
                throw;
            }
        }
    }
}
